<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function ListNode(val, next) {
        this.val = val === undefined ? 0 : val
        this.next = next === undefined ? null : next
      }
      /* 1--2--3--4   2--1--4--3 */
      var swapPairs = function (head) {
        //2和1交换，然后继续3和4交换
        //创建虚拟节点，最后返回的链表需要根据这个虚拟节点创造
        let dummy = new ListNode(null, head)
        let pre = dummy
        let cur = head
        let next = null
        //cur必须后面还有指针，因为是两两交换
        while (cur && cur.next) {
          //保存cur.next
          next = cur.next
          //让1指向3
          cur.next = next.next
          //需要让2指向1
          next.next = cur
          //必须保存2到链表上
          pre.next = next
          //这时候变成了 dummy--2--1--3--4
          //              pre--next--cur--3--4
          pre = cur
          cur = cur.next
        }
        return dummy
      }
    </script>
  </body>
</html>
